<template>
  <div>
    <div class="m-lgtop">
      <div class="wp1630">
        <NuxtLink to="/" class="logo"><img src="/images/logo.svg" alt="" /></NuxtLink>
        <div class="h-lang" @click="visibleLang = true">
              <global-outlined />
            </div>
        </div>
    </div>
    <!-- 切换语言弹窗 -->
    <a-modal
      class="modal-content"
      v-model:visible="visibleLang"
      title="选择地区语言"
      :width="665"
      :footer="null"
    >
      <ul class="lang-tab">
        <li v-for="(lang, index) in langs" :key="index">
          <div
            class="s"
            :class="{ active: lang.name === currentLang }"
            @click="changeLang(lang)"
          >
            {{ lang.name }}
          </div>
        </li>
      </ul>
    </a-modal>
    <div class="m-login">
      <div class="wp1630">
        <div class="left">
        <!-- <NuxtLink to="/" class="icon">
        <img src="/images/iconl11.png" alt="" class="icn" /></NuxtLink> -->
        <!-- <div class="pic" style="background-image: url(/images/lg-bg.png)"></div> -->
        <div class="txt">
          Sharing. <br>
          Value.<br>
          Vitality.
        </div>
      </div>
      <div class="right">
        <div class="formbox">
          <div class="nform-box">
            <div class="tit">登录 <b>SilentBerry</b></div>
          <div class="bl-types">
            <div @click="handleCredentialResponse()" class="item">
              <img src="/images/c-s1.svg" alt="" class="icn" />
              <!-- <div class="p">使用Google登录</div> -->
            </div>
            <div class="item" @click="btcLogin()">
              <img src="/images/c-s2.svg" alt="" class="icn" />
              <!-- <div class="p">使用BTC 登录</div> -->
            </div>
            <div @click="evmLogin()" class="item">
              <img src="/images/c-s3.svg" alt="" class="icn" />
              <!-- <div class="p">使用EVM 登录</div> -->
            </div>
          </div>
          <a-divider>Or better yet</a-divider>
          <a-form layout="vertical" :model="formState">
            <a-form-item >
              <a-input
                v-model:value="formState.fieldA"
                placeholder="邮件"
              >
                <template #prefix>
                  <img src="/images/lg1.svg" alt="">
                </template>
              </a-input>
            </a-form-item>
            <a-form-item>
              <div class="posr">
                <a-input
                  v-model:value="formState.fieldC"
                  type="password"
                  placeholder="密码"
                >
                  <template #prefix>
                    <img src="/images/lg2.svg" alt="">
                  </template>
                </a-input>
                <!-- <div class="code-btn" :class="{'disabled':!flag}" @click="settime()">{{text}}</div> -->
              </div>
            </a-form-item>
          </a-form>
          <div class="f-btn" @click="loginByPass()">登录账户</div>
          </div>

          <div class="nform-bot">
            <div class="f-tips">新用户首次登录我们将自动为您注册一个新的账户</div>
          <div class="ff-info">登录 即表示您同意我们的 <NuxtLink to="/richtxt">《隐私政策》</NuxtLink><NuxtLink to="/richtxt">《服务条款》</NuxtLink>。<br>本网站受recaptcha保护，并使用Google隐私政策和服务条款</div>
          </div>
        </div>
      </div>
      </div>
    </div>

    <!-- 二维码弹窗 -->
    <a-modal
      class="modal-content1"
      v-model:visible="visible"
      centered
      :width="420"
      :footer="null"
    >
    
      <div class="lg-qr">
        <div class="tit">钱包链接</div>
        <div class="qr">
          <img src="/images/f-qr.png" alt="">
        </div>
        <div class="p">使用您的移动钱包或手机相机扫描此二维码进行连接。</div>
      </div>
    </a-modal>
    <!-- 二维码弹窗end -->
  </div>
</template>

<script setup>
import { reactive, ref, onMounted,onBeforeUnmount} from 'vue';
import Cookies from 'js-cookie';
import request from '~/services/request'
import { message } from 'ant-design-vue';
import { useNuxtApp } from '#app'  
import {RouterLink, RouterView, useRouter} from 'vue-router'
const { $config } = useNuxtApp()
const router = useRouter()
const formState = reactive({
  fieldA: '',
  fieldB: '',
  fieldC: '',
});
const provider=ref(null)
const flag = ref(true);
const text = ref("获取验证码");
const login=()=>{
  request.auth_magicLinkLogin({"email": formState.fieldA,token:formState.fieldC})
  .then(res => {
    Cookies.set('login-type','email')
    Cookies.set('user-tk',res.accessToken)
    request.get_users_me().then(res => {
      Cookies.set('user-data',JSON.stringify(res))
      request.api_author_my().then(res2=>{
        Cookies.set('author-status',res2.status)
      })
      message.success({
    content: () => '登陆成功',
    class: 'custom-class',
    style: {
      marginTop: '20vh',
    },
  });
      router.push('/');
    })
  })
}
const loginByPass=()=>{
  request.auth_login({"email": formState.fieldA,password:formState.fieldC})
  .then(res => {
    Cookies.set('login-type','email')
    Cookies.set('user-tk',res.accessToken)
    request.get_users_me().then(res => {
      Cookies.set('user-data',JSON.stringify(res))
      request.api_author_my().then(res2=>{
        Cookies.set('author-status',res2.status)
      })
      message.success({
    content: () => '登陆成功',
    class: 'custom-class',
    style: {
      marginTop: '20vh',
    },
  });
      router.push('/');
    })
  })
}
const handleCredentialResponse=(response)=>{
// Google's OAuth 2.0 endpoint for requesting an access token
var oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';

// Create <form> element to submit parameters to OAuth 2.0 endpoint.
var form = document.createElement('form');
form.setAttribute('method', 'GET'); // Send as a GET request.
form.setAttribute('action', oauth2Endpoint);

// Parameters to pass to OAuth 2.0 endpoint.
var params = {'client_id': process.env.client_id,
              'redirect_uri': 'http://localhost:3000/api/auth/google/callback',
              'response_type': 'token',
              'scope': 'https://www.googleapis.com/auth/drive.metadata.readonly',
              'include_granted_scopes': 'true',
              'state': 'pass-through value'};

// Add form parameters as hidden input values.
for (var p in params) {
  var input = document.createElement('input');
  input.setAttribute('type', 'hidden');
  input.setAttribute('name', p);
  input.setAttribute('value', params[p]);
  form.appendChild(input);
}

// Add form to page and submit it to open the OAuth 2.0 endpoint.
document.body.appendChild(form);
form.submit();
}
const evmLogin=async ()=>{
  if (typeof window.ethereum !== 'undefined') {  
    try {  
      debugger
      // 请求访问权限  
      await window.ethereum.request({ method: 'eth_requestAccounts' });  
      const transaction = {  
    to: '0x1234567890123456789012345678901234567890',  
    value: '0x0',  
    gas: '0x5208',  
    // 添加其他交易参数  
  };  
      provider.value = window.ethereum;  
      const accounts = await provider.value.request({ method: 'eth_accounts' });  
      if (accounts.length > 0) {  
        request.get_auth_signKey_id({id:accounts[0]}).then(async (res)=>{
          const signature = await provider.value.request({  
          method: 'personal_sign',  
          params: [res, accounts[0]],  
        });  
       request.post_auth_verifySign({ckbAddress:accounts[0],signature:signature,signType:'EvmPersonal'}).then(res=>{
        Cookies.set('user-tk',res.accessToken)
        Cookies.set('login-type','EvmPersonal')
    request.get_users_me().then(res1 => {
      Cookies.set('user-data',JSON.stringify(res1))
      request.api_author_my().then(res2=>{
        Cookies.set('author-status',res2.status)
      })
      message.success({
    content: () => '登陆成功',
    class: 'custom-class',
    style: {
      marginTop: '20vh',
    },
  });
      router.push('/');
    })
       })
        })
      } else {  
        console.error('No Ethereum accounts found');  
        return null;  
      }  
      // const signedTransaction = await provider.value.request({  
      //   method: 'eth_sendTransaction',  
      //   params: [transaction],  
      // });  
      // console.log(signedTransaction )
    } catch (error) {  
      console.error('Error connecting to MetaMask:', error);  
    }  
  } else {  
    alert('没有钱包插件！')
  }  
}
const btcLogin=async ()=>{
  const transaction = {  
    to: '0x1234567890123456789012345678901234567890',  
    value: '0x0',  
    gas: '0x5208',  
    // 添加其他交易参数  
  };  
  if (typeof window.unisat === 'undefined') {
  	// Element-ui Message 组件
    alert('没有钱包插件！')
    return false
  }
  else {
    try {
      const accounts = await window.unisat.requestAccounts()
     // console.log('链接成功', accounts)
      const r = await window.unisat.getAccounts()
      // console.log('钱包', r)
      const publicKey = await window.unisat.getPublicKey()
      request.get_auth_signKey_id({id:r}).then(async (res)=>{
        const sign = await window.unisat.signMessage(`${res}`)
       request.post_auth_verifySign({ckbAddress:r[0],signature:sign,signType:'BtcEcdsa',btcPublicKey:publicKey}).then(res=>{
        Cookies.set('login-type','BtcEcdsa')
        Cookies.set('user-tk',res.accessToken)
    request.get_users_me().then(res1 => {
      Cookies.set('user-data',JSON.stringify(res1))
      console.log(JSON.parse(Cookies.get('user-data')))
      request.api_author_my().then(res2=>{
        Cookies.set('author-status',res2.status)
      })
      message.success({
    content: () => '登陆成功',
    class: 'custom-class',
    style: {
      marginTop: '20vh',
    },
  });
      router.push('/');
    })
       })
        })
//         window.unisat.signTransaction(transaction).then(signedTransaction => {
//     console.log('Signed transaction:', signedTransaction);
// }).catch(error => {
//     console.error('Failed to sign transaction:', error);
// });

// const transaction = { /* transaction details */ };
// window.unisat.sendTransaction(transaction).then(response => {
//     console.log('Transaction sent:', response);
// }).catch(error => {
//     console.error('Failed to send transaction:', error);
// });
     // console.log('签名', sign)      
    } catch (err) {
      console.log(err, 'err')
    }
  }
}

const getCode=()=>{
  request.send_auth_magicLink({"email": formState.fieldA})
  .then(res => {
    message.success({
    content: () => '发送成功',
    class: 'custom-class',
    style: {
      marginTop: '20vh',
    },
  });
  })
}
const settime = () => {
  getCode()
  var num = 121;

  if (flag.value) {
   
    flag.value = false;
    var timer = setInterval(function () {
      num--;
      if (num <= 0) {
        clearInterval(timer);
       
        text.value = "重新发送";
        flag.value = true;
      } else {
        
        text.value =  num + "s";
      }
    },
      1000)
  } else {
    return false;
  }


}

// 二维码弹窗
const visible = ref(false);

onMounted(() => {
  document?.querySelector('.pagebox').classList.add('pt0','page-lg');
});
onBeforeUnmount(() => {
 document?.querySelector('.pagebox').classList.remove('pt0','page-lg');
});

import { GlobalOutlined } from '@ant-design/icons-vue';
const visibleLang = ref(false)
const langs = [{ name: '简体中文', value: 'chinese_simplified' }, { name: '英语', value: 'english' }, { name: '日语', value: 'japanese' }, { name: '法语', value: 'french' },];

const changeLang = (lang) => {
  currentLang.value = lang.name
  loading.value = true
  console.log(lang.value);
  /* var loclang = localStorage.getItem('silentberrylang')
  if (lang.value === loclang) {
    // alert(1)
    // window.translate.changeLanguage(lang.value);
  } else {
    window.localStorage.setItem('silentberrylang', lang.value);
    window.translate?.changeLanguage(lang.value);
  } */
  setTimeout(() => {
    loading.value = false
    visible.value = false
  }, 300)
}
</script>

